package cn.itcast.java.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.*;

/**
 * Author itcast
 * Date 2021/10/14 11:03
 * Desc TODO
 */
public class PreparedStateDemo {
    private static ComboPooledDataSource dataSource = null;
    private static Connection conn = null;
    private static Statement statement = null;
    public static void main(String[] args) throws SQLException {
        //1.加载jar包 jdbc ，com.mysql.jdbc.Driver
        try {
            dataSource = new ComboPooledDataSource("src/c3p0-config.xml");
            //4.创建查询sql
            String sql = "SELECT * FROM category";
            //创建连接
            conn = dataSource.getConnection();
            //3.创建statement
            // PreparedStatement 是 Statement 的子类
            statement = conn.createStatement();
            //给参数赋值
//            statement.setString(1,"电脑");
            //5.执行查询操作，获取数据集 ResultSet
            // statement.execute(sql) 如果能够返回第一条数据就返回 true; 否则update delete 都返回 false
            // statement.executeUpdate(sql) 更新和插入,删除操作会返回影响的记录行数;如果是数据库的
            // DDL 操作，返回nothing 值
            // statement.executeQuery(sql) 执行查询操作,返回ResultSet结果集
            // 返回记录数，如果当前返回记录数 >=1 说明当前用户存在，登录成功！
            ResultSet rs = statement.executeQuery(sql);
            while(rs.next()){
                int cid = rs.getInt(1);
                String cname = rs.getString(2);
                System.out.println(cid+","+cname);
            }
            //6.遍历数据集并将结果打印输出
            // rs.next() : 如果当前有下一条数据就返回为true，否则为false

        } catch (SQLException e) {
            e.printStackTrace();
        }
        //7.关闭数据集，statement，connection连接
        finally {
            //if(!conn.isClosed()) conn.isClosed();
            //if(!statement.isClosed()) statement.close();
        }

    }
}
